package com.wn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wn.bean.Constants;
import com.wn.bean.House;
import com.wn.bean.PageBean;
import com.wn.bean.R;
import com.wn.service.IHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-20
 */
@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    private IHouseService houseService;

    /**
     * 分页查询:
     * 01  配置 分页插件
     *
     * 02 拿到前端的分页数据
     *
     * 03 创建 page对象 (currentPage,pageSize)
     *      IPage<House> page = new Page<>(currentPage,pageSize);
     * 04 调用分页方法
     *     IPage<House> housePage = houseService.page(page);
     * 05 组装数据返回结果
     *
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping
    public R queryHouse(Integer currentPage,Integer pageSize,Integer numbers){

        IPage<House> page = new Page<>(currentPage,pageSize);

        //条件查询
        QueryWrapper<House> qr = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(numbers)){
            qr.eq("numbers",numbers);
        }
        IPage<House> housePage = houseService.page(page,qr);

        List<House> records = housePage.getRecords();
        Long total = housePage.getTotal();

        // 组装数据返回结果

        R r = new R();

        if (!CollectionUtils.isEmpty(records)){
            PageBean<House> pageBean = new PageBean<>();
            pageBean.setData(records);
            pageBean.setTotal(total.intValue());

            r.setData(pageBean);
            r.setMsg("查询成功");
            r.setCode(Constants.SUCCESS_CODE);

            return r;
        }
        return R.ERROR("查询失败");
    }

    @PostMapping
    public R addHouse(@RequestBody House house){

        // 给默认状态
        house.setStatus(0);
        boolean save = houseService.save(house);

        if (save){
            return R.OK("添加成功...");
        }
        return R.ERROR();

    }

    @GetMapping("/all")
    public R queryHouseAll(){

        List<House> list = houseService.list();

        // 组装数据返回结果
        R r = new R();

        if (!CollectionUtils.isEmpty(list)){
            r.setData(list);
            r.setMsg("查询成功");
            r.setCode(Constants.SUCCESS_CODE);
            return r;
        }
        return R.ERROR("查询失败");
    }
}